package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.*;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcloud.vod.VodUploadClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.login.LoginContext;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

    @Autowired
    private TrackInfoMapper trackInfoMapper;
    @Autowired
    private AlbumInfoMapper albumInfoMapper;
    @Autowired
    private VodService vodService;
    @Autowired
    private TrackStatMapper trackStatMapper;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AlbumStatMapper albumStatMapper;


    /**
     * 保存声音
     *
     * @param trackInfoVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTrackInfo(Long userId, TrackInfoVo trackInfoVo) {
        //根据专辑ID查询专辑信息
        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfoVo.getAlbumId());
        //获取包含声音总数
        Integer includeTrackCount = albumInfo.getIncludeTrackCount();

        //保存声音
        TrackInfo trackInfo = BeanUtil.copyProperties(trackInfoVo, TrackInfo.class);
        trackInfo.setUserId(userId);
        //处理排序字段
        trackInfo.setOrderNum(includeTrackCount + 1);
        //处理声音媒体信息
        //处理声音媒体信息 media_duration  media_size  media_type
        TrackMediaInfoVo trackMediaInfoVo = vodService.getTrackMediaInfo(trackInfoVo.getMediaFileId());
        //判断
        if (trackMediaInfoVo != null) {
            trackInfo.setMediaDuration(new BigDecimal(trackMediaInfoVo.getDuration()));
            trackInfo.setMediaSize(trackMediaInfoVo.getSize());
            trackInfo.setMediaType(trackMediaInfoVo.getType());
        }
        trackInfo.setSource(SystemConstant.TRACK_SOURCE_USER);
        trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);
        trackInfoMapper.insert(trackInfo);
        Long id = trackInfo.getId();

        //保存统计声音
        this.initTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PLAY);
        this.initTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COLLECT);
        this.initTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PRAISE);
        this.initTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COMMENT);

        //修改专辑声音数目
        albumInfo.setIncludeTrackCount(includeTrackCount + 1);
        albumInfo.setUpdateTime(new Date());
        albumInfoMapper.updateById(albumInfo);

    }

    /**
     * 获取当前用户声音分页列表
     *
     * @param trackListVoPage
     * @param query
     * @return
     */
    @Override
    public Page<TrackListVo> findUserTrackPage(Page<TrackListVo> trackListVoPage, TrackInfoQuery query) {
        return trackInfoMapper.selectUserTrackPage(trackListVoPage, query);
    }

    /**
     * 删除声音信息
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeTrackInfo(Long id) {

        TrackInfo trackInfo = trackInfoMapper.selectById(id);
        Long albumId = trackInfo.getAlbumId();
        //1.更新专辑声音数
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);
        albumInfo.setUpdateTime(new Date());
        albumInfoMapper.updateById(albumInfo);
        //删除声音信息
        trackInfoMapper.deleteById(id);
        //删除声音后修改排序字段
        trackInfoMapper.updateOderNum(albumId, trackInfo.getOrderNum());
        //删除声音统计信息
        trackStatMapper.delete(new QueryWrapper<TrackStat>().eq("track_id", id));


        //vod删除媒体信息
        // vodService.deleteMediaByMediaFileId(trackInfo.getMediaFileId());

    }

    @Override
    public void updateTrackInfo(Long id, TrackInfoVo trackInfoVo) {
        TrackInfo trackInfo = trackInfoMapper.selectById(id);
        String oldMediaFileId = trackInfo.getMediaFileId();
        String newMediaFileId = trackInfoVo.getMediaFileId();
        BeanUtil.copyProperties(trackInfoVo, trackInfo);
        if (!oldMediaFileId.equals(newMediaFileId)) {
            TrackMediaInfoVo trackMediaInfoVo = vodService.getTrackMediaInfo(newMediaFileId);
            //判断
            if (trackMediaInfoVo != null) {
                trackInfo.setMediaDuration(new BigDecimal(trackMediaInfoVo.getDuration()));
                trackInfo.setMediaSize(trackMediaInfoVo.getSize());
                trackInfo.setMediaType(trackMediaInfoVo.getType());
            }
        }
        trackInfo.setId(id);
        trackInfo.setUpdateTime(new Date());
        trackInfoMapper.updateById(trackInfo);

    }

    /**
     * 查询专辑声音分页列表
     *
     * @param trackListVoPage
     * @param albumId
     * @param userId
     * @return
     */
    @Override
    public Page<AlbumTrackListVo> findAlbumTrackPage(Page<AlbumTrackListVo> albumTrackListVoPage, Long albumId, Long userId) {
        //专辑信息
        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
        // trackinfo表 trackstat表 一对多 track_id inner join album_id is_delete order_by track_id
        Page<AlbumTrackListVo> albumTrackPage = trackInfoMapper.findAlbumTrackPage(albumTrackListVoPage, albumId);

        //没登录获取
        if (userId == null) {
            if (SystemConstant.ALBUM_PAY_TYPE_VIPFREE.equals(albumInfo.getPayType()) || SystemConstant.ALBUM_PAY_TYPE_REQUIRE.equals(albumInfo.getPayType())) {
                albumTrackPage.getRecords().stream().filter(albumTrackListVo -> albumTrackListVo.getOrderNum() > albumInfo.getTracksForFree())
                        .forEach(albumTrackListVo -> albumTrackListVo.setIsShowPaidMark(true));
            }
        } else {
//            //非判断
//            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
//            Boolean flags= false;
//            if(userInfoVo.getIsVip().intValue()==0){
//
//
//            }
//            if(userInfoVo.getIsVip().intValue()==1&&new Date().after(userInfoVo.getVipExpireTime())){
//
//            }
            //定义变量，标识是否调用远程是否购买结果  false不调用

            boolean isNeedCheckPayStatus = false;

            //处理vip类型专辑
            if (SystemConstant.ALBUM_PAY_TYPE_VIPFREE.equals(albumInfo.getPayType())) {

                UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
                Assert.notNull(userInfoVo, "查询用户信息异常，用户id：{}", userId);
                if (userInfoVo.getIsVip().intValue() == 0) {
                    isNeedCheckPayStatus = true;
                }
                if (userInfoVo.getIsVip().intValue() == 1 && new Date().after(userInfoVo.getVipExpireTime())) {
                    isNeedCheckPayStatus = true;
                }
            }
            //处理付费
            if (SystemConstant.ALBUM_PAY_TYPE_REQUIRE.equals(albumInfo.getPayType())) {
                isNeedCheckPayStatus = true;
            }
            if (isNeedCheckPayStatus) {
                //获取待校验声音列表
                List<AlbumTrackListVo> waitCheckTrackList = albumTrackListVoPage.getRecords().stream().filter(albumTrackListVo -> albumTrackListVo.getOrderNum() > albumInfo.getTracksForFree()).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(waitCheckTrackList)) {
                    return albumTrackListVoPage;
                }
                //获取待校验声音id列表
                List<Long> waitCheckTrackIdList = waitCheckTrackList.stream().map(albumTrackListVo -> albumTrackListVo.getTrackId()).collect(Collectors.toList());
                //调用查询是否购买接口，获取购买结果
                Map<Long, Integer> checkResultMap = userFeignClient.userPaidTrack(waitCheckTrackIdList, userId, albumId).getData();
                Assert.notNull(checkResultMap, "声音是否购买校验异常");
                //遍历购买结果，拦截显示声音权限
                waitCheckTrackList.forEach(albumTrackListVo -> {
                    //获取当前声音的校验结果
                    Integer number = checkResultMap.get(albumTrackListVo.getTrackId());
                    //判断结果如果为0，设置为true
                    if (number.intValue() == 0) {
                        albumTrackListVo.setIsShowPaidMark(true);
                    }
                });
            }


        }
        return albumTrackPage;
    }

    /**
     * //声音播放量统计
     * //一天统计一次
     * @param trackStatMqVo
     */
    @Override
    public void updateTrackStat(TrackStatMqVo trackStatMqVo) {

        //设置唯一值的key 防止重复提交 setnx
        String key = "mq:" + trackStatMqVo.getBusinessNo();
        Boolean flags = redisTemplate.opsForValue().setIfAbsent(key, trackStatMqVo);
        if (flags) {
            //更新统计声音播放量
            if (trackStatMqVo.getStatType().equals(SystemConstant.TRACK_STAT_PLAY)) {

                albumStatMapper.updateAlbumStatByMQ(trackStatMqVo.getAlbumId(), trackStatMqVo.getCount(), SystemConstant.ALBUM_STAT_PLAY);

            }
            if (trackStatMqVo.getStatType().equals(SystemConstant.TRACK_STAT_COMMENT)) {
                //更新专辑统计播放量
                albumStatMapper.updateAlbumStatByMQ(trackStatMqVo.getAlbumId(), trackStatMqVo.getCount(), SystemConstant.ALBUM_STAT_COMMENT);
            }

        }
    }

    @Override
    public AlbumStatVo getAlbumStatVo(Long albumId) {
        AlbumStatVo albumStatVo = trackInfoMapper.getAlbumStatVo(albumId);
        return albumStatVo;
    }

    /**
     * 获取声音统计信息
     *
     * @param trackId
     * @return
     */
    @Override
    public TrackStatVo getTrackStatVo(Long trackId) {

        return trackInfoMapper.getTrackStatVo(trackId);
    }

    private void initTrackStat(Long trackId, String statType) {
        TrackStat trackStat = new TrackStat();
        trackStat.setTrackId(trackId);
        trackStat.setStatType(statType);
        trackStat.setStatNum(0);
        trackStatMapper.insert(trackStat);
    }
}
